var datatable;// 定义一个全局的dataTable
var data;
var signal_data;
var pgw_data;
var columnJson;
var paramData;
$(function() {
	$('#table tbody').on('click', 'tr', function() {
		if ($(this).hasClass('selected')) {
			$(this).removeClass('selected');
		} else {
			datatable.$('tr.selected').removeClass('selected');
			$(this).addClass('selected');
		}
	});
	init();
	$('input[name="dimType"]').change(function(){
		//维度radiochange事件
		dimOperate();
	});
	$('input[name="timeSize"]').change(function(){
		//维度radiochange事件
		timeSizeOperate();
	})
	
	showArearList("area");
	
	if($("#jspType").val() == 'kpi_analysis'){
		var kpi_timeSize = $('#kpi_timeSize').val();
		$("input[type='radio'][name=timeSize][value='"+kpi_timeSize+"']").attr("checked",true);
	}
});
function timeSizeOperate(){
//	var timeSize = $('input:radio[name="timeSize"]:checked').val();
//	if(timeSize=='hour' || timeSize=='day'){
//		$("#singleDateDiv").hide();
//		$("#beginDateDiv,#endDateDiv").show();
//	}
//	if(timeSize=='week' || timeSize=='month'){
//		$("#beginDateDiv,#endDateDiv").hide();
//		$("#singleDateDiv").show();
//	}
}
function createColumns(dimType){
	var dynamicColumns=[];
	var preStr="<th>时间</th><th>PGW</th><th>信令类型</th>";
	var subfix="<th>请求次数</th><th>请求失败次数</th><th>请求成功率(%)</th><th>请求创建时延(s)</th>";
	var dynamicColumns=[];
	
	$("#table thead tr").empty();
	$("#table tbody").empty();
	$("#table thead tr").append(preStr);
	
	
	if(dimType==""){
		//没有选维度
	}else{
		if(dimType=="area"){
			$("#table thead tr").append("<th>地市</th>");
			dynamicColumns.push({
					data : "city_code"
				});
			var bsidChecked= $('#bsidCheckBox').is(':checked');
			if(bsidChecked){
				//选中终端类型
				$("#table thead tr").append("<th>BSID</th>");
				dynamicColumns.push({
						data : "bsid"
					});
			}
			$("#table thead tr").append("<th>基站名称</th>");
			dynamicColumns.push({
					data : "enodeb_name"
				});
//			var enodeidbBox =$('#enodeBIDCheckBox').is(':checked');
//			if(enodeidbBox){
//				//enodeidb选中
//				$("#table thead tr").append("<th>eNodeBID</th>");
//				dynamicColumns.push({
//						data : "enodeb_id"
//					});
//			}
//			var cellNameCheckBox =$('#cellNameCheckBox').is(':checked');
//			if(cellNameCheckBox){
//				//小区选中
//				$("#table thead tr").append("<th>小区</th>");
//				dynamicColumns.push({
//						data : "cell_name"
//					});
//			}
		}
		if(dimType=="user"){
			 $("#table thead tr").append("<th>MSISDN</th><th>IMSI</th>");
			 dynamicColumns.push({
					data : "msisdn"
				});
			 dynamicColumns.push({
					data : "imsi"
				});	
		}
		if(dimType=="terminal"){
			$("#table thead tr").append("<th>终端类型</th>");
//			 $("#table thead tr").append("<th class=currentClass>终端型号</th>");
//			 columns.push({
//					data : "terminal_brand",
//					dynamic:true,
//				});
			dynamicColumns.push({
					data : "terminal_model",
				});
		}
	
	}
	$("#table thead tr").append(subfix);
//	var ht=$("#table thead tr").html();
//	alert(ht);
	var preColumns=[
					{
						data : "report_date"
					},
					{
						data : "drive_name"
					},
					{
						data : "procedure_type",
						render:function(value,type,row){
							var procedureName='';
			            	for(var j=0;j<signal_data.length;j++){
			            		var tempValue=signal_data[j].value;
			            		if(tempValue==value){
			            			procedureName=signal_data[j].label;
			            			break;
			            		}
			            	}
							return procedureName;
						}
					}
					];
	var subColumns=[
	                {
					data : "total_count"
					},
					{
						data : "failure_count",
						render : function(value, type, row) {
							var dateType = $('input:radio[name="timeSize"]:checked').val();
							var signalType = row.procedure_type;
							var jspType = '';
							var paramDate = row.report_date == undefined ? "" : row.report_date;
							var mme_name = row.drive_name == undefined ? "" : row.drive_name;
							
							var city_code = row.city_code == undefined ? "" : row.city_code;
							var tai = row.tai == undefined ? "" : row.tai;
							var enodeb_id = row.bsid == undefined ? "" : row.bsid;
							var enodeb_name =row.enodeb_name == undefined ? "" : row.enodeb_name;
							var cell_name =row.cell_name == undefined ? "" : row.cell_name;
							var group_id = row.group_id == undefined ? "" : row.group_id;
							var msisdn = row.msisdn == undefined ? "" : row.msisdn;
							var user_terminal = row.terminal_model == undefined ? "" : row.terminal_model;
							var terminal_brand = "";
							var apn_name = row.apn_name == undefined ? "" : row.apn_name;
							if(value==null){
								value="";
							}
							
							return "<a href='#' style=\"text-decoration: underline;\" onclick=\"forwordInterfaceFailure('"
									+ dateType + "','"
									+ signalType +"','"
									+ jspType +"','"
									+ mme_name +"','"
									+ city_code +"','"
									+ tai +"','"
									+ enodeb_id +"','"
									+ enodeb_name +"','"
									+ cell_name +"','"
									+ group_id +"','"
									+ msisdn +"','"
									+ user_terminal +"','"
									+ terminal_brand +"','"
									+ apn_name +"','"
									+ paramDate
									+ "')\"  >" + value + "</a>";
						}
					},
					{
						data : "success_rate"
					},
				    {
						data : "delay_time"
					}
					];
	var columns= preColumns.concat(dynamicColumns).concat(subColumns);   
	return columns;
}
function getList(){
	var timeSize = $('input:radio[name="timeSize"]:checked').val();
	var beginDate = $("#beginDate").val();
	var endDate = $("#endDate").val();
	var singleDate=$("#singleDate").val();
	var dimType = $('input:radio[name="dimType"]:checked').val();
	var city_code;
	var bsid;
	var bsidChecked=false;
	var msisdn;
	var terminalBrand;
	var terminalModel;
	var driveId=$("#pgwDiv").val();
	var signalId=$("#signalDiv").val();
	if(null==dimType || dimType==undefined){
		dimType="";
	}else{
		if(dimType=="area"){
			city_code=$("#area").val().trim();
			var checkFlag= $('#bsidCheckBox').is(':checked');
			if(checkFlag){
				bsidChecked=true;
				bsid=$("#bsid_input").val().trim();
//				if(bsid==""){
//					alert("勾选的BSID输入内容不能为空！");
//					return;
//				}
			}else{
				bsid="";
			}
		}
		if(dimType=="user"){
			msisdn=$("#MSISDN").val().trim();		
//			if(msisdn==""){
//				alert("MSISDN内容不能为空！");
//				return;
//			}
		}
		if(dimType=="terminal"){
			terminalBrand=$("#brandDiv").val();
			terminalModel=$("#modelDiv").val();
			if(terminalBrand==null || terminalBrand==''){
				terminalBrand = "all";
			}
			if(terminalModel=="全部"){
				terminalModel="";//当没有点击品牌的时候，型号没有值，所以值会是全部
			}
			
		}
	}
	var city_code=$("#area").val();
	if(beginDate==""){
		alert("请选择开始时间！");
		return;
	}
	if(endDate==""){
		alert("请选择结束时间！");
		return;
	}
	
	var beginDate1 = new Date(beginDate.replace(/-/g,"/"));
	var endDate2 = new Date(endDate.replace(/-/g,"/"));
	if((beginDate1-endDate2)>0){
		alert("开始时间不能大于或等于结束时间！");
		return;
	}
//	 if(timeSize=="hour" ||timeSize=="day"){
//		 //自定义
//			if(beginDate==""){
//				alert("请选择开始时间！");
//				return;
//			}
//			if(endDate==""){
//				alert("请选择结束时间！");
//				return;
//			}
//			
//			var beginDate1 = new Date(beginDate.replace(/-/g,"/"));
//			var endDate2 = new Date(endDate.replace(/-/g,"/"));
//			if((beginDate1-endDate2)>0){
//				alert("开始时间不能大于或等于结束时间！");
//				return;
//			}
//	 }else{
//			if(singleDate==""){
//				alert("请选择日期！");
//				return;
//			}
//			beginDate=singleDate;
//			endDate=singleDate;
//	 }
	//$("#table tbody tr").remove();
	$("#tbodyId").remove();
	$('#table').append($("<tbody id='tbodyId'></tbody>"));
	if (datatable == undefined || datatable == "undefined" || datatable == null) {
	} else {
		datatable.fnDestroy();
	}
	var columns=createColumns(dimType);
	columnJson=dealColumnJson(columns);
	datatable = $('#table')
			.dataTable(
					{
						"aoColumnDefs" : [ {
							sDefaultContent : '',
							aTargets : [ '_all' ]
						} ],
						"bPaginate" : true, // 翻页功能
						"bLengthChange" : false, // 改变每页显示数据数量
						"bFilter" : false, // 过滤功能
						"bSort" : true, // 排序功能
						"bInfo" : true,// 页脚信息
						"iDisplayLength" : 50,
						"bAutoWidth" : true,// 自动宽度
						// "sPaginationType": "full_numbers",//显示分页的样式
						// 还有simple_numbers等
						"iDisplayLength" : 50,
//						"sScrollX" : "100%",
						"sScrollXInner" : "110%",
						"bScrollCollapse" : true,
						"oLanguage" : {
							"sLengthMenu" : "每页显示 _MENU_条",
							"sZeroRecords" : "没有找到符合条件的数据",
							"sProcessing" : "&nbsp;&nbsp;&nbsp;&nbsp;查询中，请稍等...",
							"sInfo" : "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
							"sInfoEmpty" : "没有记录",
							"sInfoFiltered" : "(从 _MAX_ 条记录中过滤)",
							"sSearch" : "搜索：",
							"oPaginate" : {
								"sFirst" : "首页",
								"sPrevious" : "前一页",
								"sNext" : "后一页",
								"sLast" : "尾页"
							}
						},
						"bProcessing" : true,
						"bServerSide" : true,
						"sAjaxSource" : "../../businessAnalysis/eHRPD/getList",
						"fnServerData" : function(sSource, aoData, fnCallback) {
							paramData={
									"aoData" : JSON.stringify(aoData),
									"timeSize" : timeSize,
									"beginDate" : beginDate,
									"endDate" : endDate,
									"dimType" : dimType,
									"cityCode" : city_code,
									"driveId" : driveId,
									"signalId":signalId,
									"bsid" : bsid,
									"msisdn" : msisdn,
									"bsidChecked":bsidChecked,
									"terminalBrand" : terminalBrand,
									"terminalModel" : terminalModel
								};
							$.ajax({
										"type" : "post",
										"contentType" : "application/x-www-form-urlencoded",
										"url" : sSource,
										"dataType" : "json",
										"data" : paramData, // 以json格式传递
										"success" : function(resp) {
											fnCallback(resp.pageDate);
											data = resp.allData;
										}
									});
						},
						columns :columns

					});
}
function removeColumns(con){
	var flag=false;
	for(var k=0;k<columns.length;k++){
		var obj=columns[k];
		if(obj.dynamic==true){
			flag=true;
			break;
		}
	}
	if(flag){
		for(var l=0;l<con;l++){
			columns.pop();
		}
	}
	
}
function dimOperate(){
//	 $("#table thead tr").empty();
//	 var thstr="<th>时间</th><th>PGW</th><th>信令类型</th><th>请求次数</th><th>请求失败次数</th><th>请求成功率</th><th>请求创建时延</th>"
//	 $("#table thead tr").append(thstr);
	 var dimType=$('input[name="dimType"]:checked ').val();
	 if(dimType=="area"){
//		  removeColumns(2);
//		 $("#table .currentClass").remove();
//		 $("#table thead tr").append("<th class=currentClass>BSID</th>");
//		 $("#table thead tr").append("<th class=currentClass>地市</th>");
//		 columns.push({
//				data : "bsid",
//				dynamic:true
//			});
//		 columns.push({
//				data : "city_code",
//				dynamic:true
//			});
		 $(".dimuser").hide();
		 $(".dimterminal").hide();
	 }
	 if(dimType=="user"){
//		 removeColumns(2);
//		 $("#table .currentClass").remove();
//		 $("#table thead tr").append("<th class=currentClass>MSISDN</th>");
//		 $("#table thead tr").append("<th class=currentClass>IMSI</th>");
//		 columns.push({
//				data : "msisdn",
//				dynamic:true
//			});
//		 columns.push({
//				data : "imsi",
//				dynamic:true
//			});
		 $(".dimarea").hide();
		 $(".dimterminal").hide();
	 }
	 if(dimType=="terminal"){
//		 removeColumns(1);
//		 $("#table .currentClass").remove();
//		 $("#table thead tr").append("<th class=currentClass>终端品牌</th>");
//		 $("#table thead tr").append("<th class=currentClass>终端型号</th>");
//		 columns.push({
//				data : "terminal_brand",
//				dynamic:true,
//			});
//		 columns.push({
//				data : "terminal_model",
//				dynamic:true
//			});
		 $(".dimarea").hide();
		 $(".dimuser").hide();
	 }
	 $(".dim"+dimType).show();
}
function init(){
	$(".dimuser").hide();
	$(".dimterminal").hide();
	$(".dimarea").hide();
	$("#singleDateDiv").hide();
	$("#pgwDiv").jqxComboBox({promptText: "全部",width: 225,height: 25});
	$("#signalDiv").jqxComboBox({promptText: "全部",width: 225,height: 25});
	$("#brandDiv").jqxComboBox({promptText: "全部",width: 225,height: 25});
	$("#modelDiv").jqxComboBox({promptText: "全部",width: 225,height: 25});
	  pgw_data=new Array() ;
	  var pgwsource =
	    {
	        datatype: "json",
	        datafields: [
	            { name: 'drive_id' },
	            { name: 'drive_name' }
	        ],
	        url: "../../businessAnalysis/eHRPD/getDriveList",
	        async: false
	    };
	    var pgwAdapter = new $.jqx.dataAdapter(pgwsource);

	    // 信令类型名称
	    $("#pgwDiv").jqxComboBox(
	    { 
	    	source: pgwAdapter, 
	    	promptText: "全部",
	    	displayMember: "drive_name", 
	    	valueMember: "drive_id", 
	    	width: 225, 
	    	height: 25,
	    	autoComplete: true,
	    	renderer: function (index, label, value) {
	    		
                var item = pgwAdapter.records[index];
                
                if (item != null) {

                    var label = item.drive_name ;
                    pgw_data[index]=item;
                    return label;

                }
                	return "";


            }
	    });
	    $("#pgwDiv").val("");
		
		  var signalsource =
		    {
		        datatype: "json",
		        datafields: [
		            { name: 'value' },
		            { name: 'label' }
		        ],
		        url: "../../businessAnalysis/eHRPD/getSignalList",
		        async: false
		    };
		    var signalAdapter = new $.jqx.dataAdapter(signalsource);
		    signal_data=new Array() ;
		    // 信令类型名称
		    $("#signalDiv").jqxComboBox(
		    { 
		    	source: signalAdapter, 
		    	promptText: "全部",
		    	displayMember: "label", 
		    	valueMember: "value", 
		    	width: 225, 
		    	height: 25,
		    	autoComplete: true,
		    	renderer: function (index, label, value) {
		    		
                    var item = signalAdapter.records[index];
                    
                    if (item != null) {

                        var label = item.label ;
                        signal_data[index]=item;
                        return label;

                    }
                    	return "";


                }
		    });
//		    signal_data=signalAdapter.cacherecords;
//		    alert(signalAdapter.length);
		    $("#signalDiv").val("");
		    var brandsource =
		    {
		        datatype: "json",
		        datafields: [
		            { name: 'value' },
		            { name: 'label' }
		        ],
		        url: "../../businessAnalysis/eHRPD/getBrandList",
		        async: false
		    };
		    var brandAdapter = new $.jqx.dataAdapter(brandsource);

		    // 信令类型名称
		    $("#brandDiv").jqxComboBox(
		    { 
		    	source: brandAdapter, 
		    	promptText: "全部",
		    	displayMember: "value", 
		    	valueMember: "label", 
		    	width: 225, 
		    	height: 25,
		    	autoComplete: true
		    });
		    $("#brandDiv").val("all");
		    $("#brandDiv").on('change', function (event) {
		    	getModelList($(this).val());
		    });
}

function getModelList(brandId){
	var modelsource =
    {
        datatype: "json",
        datafields: [
            { name: 'terminal_model' },
            { name: 'terminal_model' }
        ],
        url: "../../businessAnalysis/eHRPD/getModelList?brandId="+brandId,
        async: false
    };
	var modelAdapter = new $.jqx.dataAdapter(modelsource);

    // 信令类型名称
    $("#modelDiv").jqxComboBox(
    { 
    	source: modelAdapter, 
    	promptText: "全部",
    	displayMember: "terminal_model", 
    	valueMember: "terminal_model", 
    	width: 225, 
    	height: 25,
    	autoComplete: true
    });
}
//下拉树 begin
function onClick(e, treeId, treeNode) {
	var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
	nodes = zTree.getSelectedNodes(),
	v = "";
	nodes.sort(function compare(a,b){return a.id-b.id;});
	for (var i=0, l=nodes.length; i<l; i++) {
		v += nodes[i].name + ",";
	}
	if (v.length > 0 ) v = v.substring(0, v.length-1);
	var cityObj = $("#citySel");
	cityObj.attr("value", v);
	$("#area").val(treeNode.id);
	
	hideMenu();
}
/**
 * 显示树
 */
function showMenu() {
	var cityObj = $("#citySel");
	var cityOffset = $("#citySel").offset();
	$("#menuContent").css({left:cityOffset.left-26 + "px", top:cityOffset.top-206 + "px"}).slideDown("fast");

	$("body").bind("mousedown", onBodyDown);
}
/**
 * 隐藏树
 */
function hideMenu() {
	$("#menuContent").fadeOut("fast");
	$("body").unbind("mousedown", onBodyDown);
}
function onBodyDown(event) {
	if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
		hideMenu();
	}
}
function exportExcel() {
	if(paramData==undefined ||paramData==null ||paramData==''){
		alert("请先点击查询，然后导出！");
		return;
	}
	var countRecord = $("#table tbody tr :not(.dataTables_empty)").length;//总行数  
	if(countRecord==0){
		alert("没有可导出符合条件的的数据！");
		return;
	}
	paramData["columnJson"]=JSON.stringify(columnJson);
	$.ajax({
		type : "POST",
		url : "../../businessAnalysis/eHRPD/exportExcel?rand="
				+ Math.random(),
		dataType : "json",
		"data" : paramData,
		success : function(data) {
			if (data.flag) {
				var url = "../../businessAnalysis/eHRPD/downFiles?path="
						+ data.path;
				window.location.href = url;
			} else {
				alert(data.msgs);
			}
		}
	});
}
function dealColumnJson(columns){
	
	columnJson=[];
	for(var i=0;i<columns.length;i++){
		var key=columns[i].data;
		$("#table thead tr th").each(function (index){
			var text="";
			if(index==i){
				text=$(this).text().trim();
				var jsonObj={ "key" : key.trim(),         "text" : text.trim()};
				columnJson.push(jsonObj);
			}
		});
	}
	return columnJson;
}
/**
 * 失败次数跳转到
 */
function forwordInterfaceFailure(dateType,signalType,jspType,mme_name,city_code,tai,
		enodeb_id,enodeb_name,cell_name,group_id,msisdn,user_terminal,terminal_brand,apn_name,paramDate) {
	var bsidCheck_status;
	if($("#bsidCheckBox").is(':checked')){
		bsidCheck_status=1;
	}
	var dimType = $('input:radio[name="dimType"]:checked').val();
	var url = "/kpi/interfaceFailureLink/index?dateType=" + dateType +"&failureTypeInfo=&jspType="+jspType +"&mme_name="+mme_name
	+ "&paramDate=" + paramDate + "&interfaceType=7&signalType=" + signalType + "&type=" + dimType + "&eNodeBID_status=" + bsidCheck_status 
	+ "&city_code=" +city_code+"&tai="+tai+"&enodeb_id="+enodeb_id+"&enodeb_name="+enodeb_name  
	+ "&cell_name=" +cell_name+"&group_id="+group_id+"&msisdn ="+msisdn+"&user_terminal="+user_terminal+"&terminal_brand="+terminal_brand+"&apn_name="+apn_name;   
	linkTab("接口故障", url);
}